package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.JsonResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.InfoCategory;
import com.ruoyi.system.domain.InfoCategoryInfo;
import com.ruoyi.system.service.IInfoCategoryInfoService;
import com.ruoyi.system.service.IInfoCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 新闻栏目Controller
 * 
 * @author ruoyi
 * @date 2022-12-02
 */
@Controller
@RequestMapping("/system/category")
public class InfoCategoryController extends BaseController
{
    private String prefix = "system/category";

    @Autowired
    private IInfoCategoryService infoCategoryService;

    @Autowired
    private IInfoCategoryInfoService infoCategoryInfoService;

    @PreAuthorize("@ss.hasPermi('system:category:view')")
    @GetMapping()
    public String category()
    {
        return prefix + "/category";
    }

    /**
     * 查询新闻栏目列表
     */
    /*@RequiresPermissions("system:category:list")*/
    /*@PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(InfoCategory infoCategory)
    {
        startPage();
        List<InfoCategory> list = infoCategoryService.selectInfoCategoryList(infoCategory);
        return getDataTable(list);
    }*/

    /**
     * 导出新闻栏目列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:export')")
    @Log(title = "新闻栏目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(InfoCategory infoCategory)
    {
        List<InfoCategory> list = infoCategoryService.selectInfoCategoryList(infoCategory);
        ExcelUtil<InfoCategory> util = new ExcelUtil<InfoCategory>(InfoCategory.class);
        return util.exportExcel(list, "新闻栏目数据");
    }

    /**
     * 新增新闻栏目
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存新闻栏目
     */
    /*@RequiresPermissions("system:category:add")
    @Log(title = "新闻栏目", businessType = BusinessType.INSERT)*/
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated @RequestBody InfoCategory infoCategory)
    {
        infoCategory.setCategoryid(UUID.randomUUID().toString());
        infoCategory.setAddtime(new Date());
        infoCategory.setAllowdelete(new Long(1));
        return toAjax(infoCategoryService.insertInfoCategory(infoCategory));
    }

    /**
     * 修改新闻栏目
     */
    /*@RequiresPermissions("system:category:edit")*/
    @GetMapping("/edit/{categoryid}")
    public String edit(@PathVariable("categoryid") String categoryid, ModelMap mmap)
    {
        InfoCategory infoCategory = infoCategoryService.selectInfoCategoryByCategoryid(categoryid);
        mmap.put("infoCategory", infoCategory);
        return prefix + "/edit";
    }

    /**
     * 修改保存新闻栏目
     */
    /*@RequiresPermissions("system:category:edit")
    @Log(title = "新闻栏目", businessType = BusinessType.UPDATE)*/
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody InfoCategory infoCategory)
    {
        return toAjax(infoCategoryService.updateInfoCategory(infoCategory));
    }

    /**
     * 删除新闻栏目
     */
/*    @RequiresPermissions("system:category:remove")*/
    @Log(title = "新闻栏目", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(infoCategoryService.deleteInfoCategoryByCategoryids(ids));
    }

    @GetMapping( "/findall")
    @ResponseBody
    public JsonResult<?> findAll()
    {
        try {
        List<Map<String,Object>> mmList = infoCategoryService.findAll();
        List<Map<String,Object>> mmReturnList = new ArrayList<>();
        for (int i = 0; i < mmList.size(); i++) {
            List<String> mmChildren = new ArrayList<>();
            Map<String,Object> mmMap = mmList.get(i);
            mmMap.put("children",mmChildren);
            mmReturnList.add(mmMap);
        }
        return JsonResult.getSuccessResult(mmReturnList);
        } catch (Exception e) {
            logger.error("infocategory/findall", e);
            return JsonResult.getErrorResult("infocategory/findall");
        }
    }

    @PostMapping( "/findone")
    @ResponseBody
    public InfoCategory findOne(@RequestParam("categoryid") String categoryid)
    {
        return infoCategoryService.selectInfoCategoryByCategoryid(categoryid);
    }

    @PostMapping( "/findbyparentcategoryid")
    @ResponseBody
//    @RateLimiter(count = 100, time = 60)
//    @RepeatSubmit(interval = 1000)
    public List<Map<String,Object>> findByParentcategoryid(@RequestParam("categoryid") String categoryid)
    {
        return infoCategoryService.findByParentCategoryId(categoryid);
    }

    @PostMapping( "/findallxiajibyparentcategoryid")
    @ResponseBody
    public List<Map<String,Object>> findAllXiajiByParentcategoryid(@RequestParam("categoryid") String categoryid)
    {
        List<Map<String,Object>> mmReturnList =findXiajiAll(categoryid);

        return mmReturnList;
    }

    public List<Map<String,Object>> findXiajiAll(String categoryid) {
        // 用于输出的集合
        List<Map<String,Object>> mmCategoryList = infoCategoryService.findByParentCategoryId(categoryid);
        List<Map<String,Object>> mmReturnList = new ArrayList<>();
        for (int i = 0; i < mmCategoryList.size(); i++) {
            Map<String,Object> infoCategory = mmCategoryList.get(i);
            if (infoCategory==null){
                throw new RuntimeException("in");
            }


            String mmcategoryid = infoCategory.get("categoryid")==null?"":infoCategory.get("categoryid").toString();
            // 继续查询下级
            List<Map<String,Object>> mmXiajiCategoryList = infoCategoryService.findByParentCategoryId(mmcategoryid);

            // 存在下级就继续查
            if (mmXiajiCategoryList.size() > 0) {
                List<Map<String,Object>> mmXiashuList = findXiajiAll(mmcategoryid);
                infoCategory.put("xiajicategorylist",mmXiashuList);
            }
            mmReturnList.add(infoCategory);
        }
        return mmReturnList;
    }

    @PostMapping( "/delete")
    @ResponseBody
    public AjaxResult delete(@RequestParam("categoryid") String categroyid)
    {
        InfoCategoryInfo infoCategoryInfo = new InfoCategoryInfo();
        infoCategoryInfo.setCategoryid(categroyid);
        List<InfoCategoryInfo> InfoCategoryInfoList = infoCategoryInfoService.selectInfoCategoryInfoList(infoCategoryInfo);
        if (InfoCategoryInfoList.size()>0){
            throw new RuntimeException("请先删除该栏目新闻后再删除栏目");
        }
        return toAjax(infoCategoryService.deleteInfoCategoryByCategoryid(categroyid));
    }



}
